﻿using Microsoft.AspNetCore.Mvc;
using STF.Blog.Common;
using STF.Blog.IService;
using STF.Blog.WebApp.Areas.ForumManage.Filters;
using STF.Blog.WebApp.Areas.ForumManage.Models.Level;
using X.PagedList;

namespace STF.Blog.WebApp.Areas.ForumManage.Controllers
{
    [Area("ForumManage")]
    [Login]
    public class LevelController : Controller
    {
        private ILevelService _ileSvc;
        public LevelController(ILevelService ileSvc)
        {
            _ileSvc = ileSvc;
        }
        
        [HttpGet]
        public async Task<IActionResult> Index(string search, int page = 1)
        {
            search = string.IsNullOrEmpty(search) ? "" : search;
            var data = await _ileSvc.GetByNameAsync(search);
            var LevelList = data.Select(l => new LevelListViewModel
            {
                Id = l.Id,
                Title = l.Title,
                Details = l.Details,
                CreateTime = l.CreateTime,
                UpdateTime = l.UpdateTime
            });

            ViewBag.Search = search;
            var pages = await LevelList.ToPagedListAsync(page,PageConfig.PageSize);
            return View(pages);
        }

        [HttpGet]
        public async Task<IActionResult> Add() 
        {
            return View(new LevelAddViewModel());
        }

        [HttpPost]
        public async Task<IActionResult> Add(LevelAddViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                await _ileSvc.AddLevelAsync(model.Title,model.Details);
                return Redirect("~/ForumManage/Level/Index");
            }
            return View(model);
        }

        [HttpGet]
        public async Task<IActionResult> Update(int id) 
        {
            var data = await _ileSvc.GetByIdAsync(id);
            return View(new LevelUpdateViewModel 
            {
                Id = data.Id,
                Title = data.Title,
                Details = data.Details
            });
        }

        [HttpPost]
        public async Task<IActionResult> Update(LevelUpdateViewModel model) 
        {
            if (ModelState.IsValid) 
            {
                await _ileSvc.UpdateLevelAsync(model.Id,model.Title, model.Details);
                return Redirect("~/ForumManage/Level/Index");
            }
            return View(model);
        }

        [HttpPost]
        public async Task<IActionResult> Delete(int id) 
        {
            await _ileSvc.PutTrashAsync(id);
            return Redirect("~/ForumManage/Level/Index");
        }

    }
}
